from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver_path = r'D:\lishaobai\prog\edgedriver_win64\msedgedriver.exe'
serial_num = "84220771"

driver = webdriver.Edge(service=Service(driver_path))
    # Navigate to the website

url = f'http://patientview.2m9h.net/Patient/VisitNumber/{serial_num}'
driver.get(url)

wait = WebDriverWait(driver, 10)

try:
    element = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "病历文书")))
    element.click()
except:
    print("未找到超链接文本 '病历文书'，尝试其他方法...")

try:
    div_container = wait.until(EC.presence_of_element_located((By.ID, "divContainerEmr")))
    print("divContainerEmr 已找到！")
    
    # 获取 `divContainerEmr` 的 HTML 结构，确认其加载内容
    div_html = div_container.get_attribute("outerHTML")
    print("divContainerEmr 内容预览：\n", div_html[:500])  # 只打印前500字符，避免过长
    
    # 尝试索引 `treeviewLeftData`
    tree_view = driver.find_element(By.ID, "treeviewLeftData")
    print("treeviewLeftData 已找到！")
    
    # 获取树形菜单下的所有子项
    items = tree_view.find_elements(By.CLASS_NAME, "k-item")
    print(f"发现 {len(items)} 个子项")


    for item in items:
        if "门诊病史" in item.text:
            print("找到 '门诊病史' 选项！")
            
            # 检查是否有展开按钮
            try:
                expand_icon = item.find_element(By.CLASS_NAME, "k-icon.k-plus")
                if expand_icon.is_displayed():
                    expand_icon.click()  # 点击展开
                    print("已展开 '门诊病史' 选项")
            except:
                print("'门诊病史' 可能已经展开")

            # 点击“门诊病史”
            item.click()
            print("'门诊病史' 已点击！")
            break

except Exception as e:
    print("divContainerEmr 未找到！")
    print("错误信息：", str(e))

print("OK")
time.sleep(10)

driver.quit()